#!/usr/bin/env python

import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api.labs import taskqueue
from google.appengine.api import urlfetch
import xml.etree.ElementTree as ET

from google.appengine.api import memcache

from db_city import DbCity

class ControlCityGet(webapp.RequestHandler):
    def get(self):
        citys = memcache.get("citys_cache")
        if citys is not None:
            pass
        else:
            citys = DbCity.all()
            memcache.add("citys_cache", citys)
        template_values = {
          'citys': citys,
        }
        path = os.path.join(os.path.dirname(__file__), 'controlCityGet.xml')
        self.response.out.write(template.render(path, template_values))

class ControlCity(webapp.RequestHandler):
    def get(self):
        results = DbCity.all()
        for result in results:
            result.delete()

class ControlCityFakeGeo(webapp.RequestHandler):
    def get(self):
        results = DbCity.all()
        lat = 30.5
        long = 117.0
        for result in results:
            result.geo = db.GeoPt(lat, long)
            lat = lat + 0.1
            long = long + 0.1
            db.put(result)

class ControlCityGeo(webapp.RequestHandler):
    def get(self):
        citys = memcache.get("citys_cache")
        if citys is not None:
            pass
        else:
            citys = DbCity.all()
            memcache.add("citys_cache", citys)
        for city in db_city_query:
            taskqueue.add(url='/controlCityGeoTask', params={'woeid': city.woeid_weather})

class ControlCityGeoTask(webapp.RequestHandler):
    def post(self):
    #def get(self):
        woeid = self.request.get('woeid')
        url = "http://where.yahooapis.com/v1/place/" + woeid + "?appid=h4EkpNPIkY3Vy4V3hLwjFnRUjoRZ595o7w--"
        #url = "http://where.yahooapis.com/v1/place/12712768?appid=h4EkpNPIkY3Vy4V3hLwjFnRUjoRZ595o7w--"
        result = urlfetch.fetch(url=url)
        result_xml = ET.fromstring(result.content)
        centroid = result_xml.find('{http://where.yahooapis.com/v1/schema.rng}centroid')
        lat = centroid.find('{http://where.yahooapis.com/v1/schema.rng}latitude').text
        long = centroid.find('{http://where.yahooapis.com/v1/schema.rng}longitude').text
        #self.response.out.write(lat+"  "+long)
        city = DbCity.all().filter("woeid_weather =", woeid)
        #city = DbCity.all().filter("woeid_weather =", "12712768")
        try:
            for i in city:
                #self.response.out.write(i.name)
                i.geo = db.GeoPt(lat, long)
                db.put(i)
        except:
            self.response.out.write("wrong")


def main():
  application = webapp.WSGIApplication([('/controlCity', ControlCity),
                                        ('/controlCityFakeGeo', ControlCityFakeGeo),
                                        ('/controlCityGeo', ControlCityGeo),
                                        ('/controlCityGeoTask', ControlCityGeoTask),
                                        ('/controlCityGet', ControlCityGet),
                                        ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()